import 'package:flutter/material.dart';
import 'package:projectfluttershengyihuatong/category/CatetoryModel.dart';
import 'package:projectfluttershengyihuatong/service/launchservice/launchservice.dart';
import 'package:projectfluttershengyihuatong/service/loginService/logginservice.dart';
import 'package:projectfluttershengyihuatong/service/request_manager.dart';
import 'package:projectfluttershengyihuatong/tab2/problemquestiontab.dart';
import 'package:projectfluttershengyihuatong/tab2/problemsolvHeader.dart';
import 'package:projectfluttershengyihuatong/tab2/problemsolvoptincell.dart';
import 'package:projectfluttershengyihuatong/tool/public_color.dart';
import 'package:projectfluttershengyihuatong/tool/tool.dart';
import 'questionlesson.dart';
import 'questionmodel.dart';
import 'package:get/get.dart';

class QBProblemSolv extends StatefulWidget {
  const QBProblemSolv({super.key});

  @override
  State<QBProblemSolv> createState() => _QBProblemSolvState();
}

class _QBProblemSolvState extends State<QBProblemSolv>
    with SingleTickerProviderStateMixin {
  late ChapterAndLesson chapterAndLesson = ChapterAndLesson();
  late CatetoryModel catetoryModel = CatetoryModel();
  late int type = 0;

  late PageController pageController;

  @override
  void initState() {
    pageController = PageController();
    // TODO: implement initState
    final dict = Get.arguments as Map<String, dynamic>;
    if (dict["1"] != null) {
      chapterAndLesson = dict["1"] as ChapterAndLesson;
    }
    if (dict["2"] != null) {
      catetoryModel = dict["2"] as CatetoryModel;
    }
    if (dict["3"] != null) {
      type = dict["3"] as int;
    }
    super.initState();
  }

  Future<Questionmodel?> request() async {
    const url = "https://test.sharedyxy.com/api/stuQuestion/getQuestion";

    final token = LoginService.getInstance().userInfo?.token ?? "";
    RequestManager.getInstance().dio.options.headers["token"] = token;
    final dict = {
      "project_id": chapterAndLesson.pid ?? 0,
      "pageSize": 10000,
      "pageNo": 1
    };
    final response =
        await RequestManager.getInstance().dio.get(url, queryParameters: dict);
    final model = Questionmodel.fromJson(response.data["data"]);
    return model;
  }

  Future<Questionmodel?> requestEveryDay() async {
    const url =
        "https://test.sharedyxy.com/api/stuQuestion/getEveryDayQuestion";

    final token = LoginService.getInstance().userInfo?.token ?? "";
    RequestManager.getInstance().dio.options.headers["token"] = token;
    final dict = {
      "kemu_id": catetoryModel.pid ?? 0,
    };
    final response =
        await RequestManager.getInstance().dio.get(url, queryParameters: dict);
    final model = Questionmodel.fromJson(response.data["data"]);
    return model;
  }

  late List<QuestionTab> widgets = [];

  @override
  Widget build(BuildContext context) {
    final safebottom = MediaQuery.of(context).padding.bottom;
    print(safebottom);
    return Scaffold(
      appBar: AppBar(
        title: Text("海量刷题"),
        backgroundColor: primaryColor,
      ),
      body: FutureBuilder(
          future: type == 1 ? requestEveryDay() : request(),
          builder: (context, snapshot) {
            if (snapshot.data != null && snapshot.hasData) {
              final dataArr = snapshot.data?.list ?? [];
              widgets = [];
              dataArr.asMap().forEach((key, element) {
                element.index = key + 1;
                widgets.add(QuestionTab(
                  dataArr: dataArr,
                  catetoryModel: catetoryModel,
                  chapterAndLesson: chapterAndLesson,
                  model: element,
                  pageController: pageController,
                ));
              });

              return Stack(
                children: [
                  Positioned(
                      left: 0,
                      right: 0,
                      top: 0,
                      height: 3,
                      child: ProgressIndicator(pageController: pageController)),
                  Positioned(
                    left: 0,
                    right: 0,
                    top: 3,
                    bottom: 40 + safebottom,
                    child: PageView.builder(
                      itemBuilder: (context, index) {
                        return widgets[index];
                      },
                      onPageChanged: (index) {},
                      itemCount: dataArr.length,
                      controller: pageController,
                    ),
                  ),
                  Positioned(
                      left: 0,
                      right: 0,
                      bottom: 0,
                      height: 40 + safebottom,
                      child: Column(
                        children: [
                          Expanded(
                              child: Container(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: [
                                IconButton(
                                    onPressed: () {
                                      if (pageController.page != null && pageController.page! > 0) {
                                        pageController.animateToPage(
                                            (pageController.page! - 1).toInt(),
                                            duration:
                                                const Duration(milliseconds: 500),
                                            curve: Curves.easeInOutSine);
                                      }
                                    },
                                    icon: Image.asset(
                                      assetImage("leftArrow1"),
                                      width: 25.adapt(),
                                    )),
                                const CustomIconButton(
                                  normalImage: "qb_collection",
                                  selectImage: "qb_collect_select",
                                  normalTitle: "收藏",
                                  selectTitle: "取消收藏",
                                ),
                                const CustomIconButton(
                                  normalImage: "tiku",
                                  selectImage: "",
                                  normalTitle: "查看答案",
                                ),
                                IconButton(
                                    onPressed: () {
                                      if (pageController.page != null && pageController.page! < (dataArr.length - 1) ) {
                                        pageController.animateToPage(
                                            (pageController.page! + 1).toInt(),
                                            duration:
                                            const Duration(milliseconds: 500),
                                            curve: Curves.easeInOutSine);
                                      }
                                    },
                                    icon: Image.asset(
                                      assetImage("rightArrow1"),
                                      width: 25.adapt(),
                                    ))
                              ],
                            ),
                          )),
                          const SizedBox(
                            height: 19,
                          ),
                        ],
                      ))
                ],
              );
            }
            return const Center(
              child: CircularProgressIndicator(
                color: Colors.red,
              ),
            );
          }),
    );
  }
}

class CustomIconButton extends StatefulWidget {
  const CustomIconButton({
    super.key,
    this.imageW = 21,
    this.imageH = 21,
    this.normalTextColor = const Color(0xff999999),
    this.selectedTextColor = const Color(0xff4bcca6),
    required this.normalImage,
    required this.selectImage,
    this.normalTitle = "",
    this.selectTitle = ""
  });
  final String normalImage;
  final String selectImage;
  final double imageW;
  final double imageH;
  final Color normalTextColor;
  final Color selectedTextColor;
  final String normalTitle;
  final String selectTitle;
  @override
  State<CustomIconButton> createState() => _CustomIconButtonState();
}

class _CustomIconButtonState extends State<CustomIconButton> {
  @override
  Widget build(BuildContext context) {
    return IconButton(
      style: const ButtonStyle(
          shape: MaterialStatePropertyAll(RoundedRectangleBorder()),
          padding: MaterialStatePropertyAll(EdgeInsets.all(3))
      ),
      onPressed: () {},
      icon: buildNormal(),
      selectedIcon: buildSelect(),
    );
  }

  Column buildNormal() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Image.asset(
          assetImage(widget.normalImage),
          width: widget.imageW.toInt().adapt(),
          height: widget.imageH.toInt().adapt(),
        ),
        const SizedBox(
          height: 3,
        ),
        Text(
          widget.normalTitle,
          style: TextStyle(color: widget.normalTextColor, fontSize: 11),
        ),
      ],
    );
  }

  buildSelect() {
    return Column(
      children: [
        Image.asset(
          assetImage(widget.selectImage),
          width: 21.adapt(),
          height: 21.adapt(),
        ),
        const SizedBox(
          height: 3,
        ),
        Text(
          widget.selectTitle,
          style: TextStyle(color: widget.selectedTextColor, fontSize: 11),
        ),
      ],
    );
  }
}

class ProgressIndicator extends StatefulWidget {
  const ProgressIndicator({
    super.key,
    required this.pageController,
  });

  final PageController pageController;

  @override
  State<ProgressIndicator> createState() => _ProgressIndicatorState();
}

class _ProgressIndicatorState extends State<ProgressIndicator> {
  @override
  void initState() {
    widget.pageController.addListener(() {
      value = widget.pageController.position.pixels /
          widget.pageController.position.maxScrollExtent;
      setState(() {});
    });
    // TODO: implement initState
    super.initState();
  }

  double value = 0;

  @override
  Widget build(BuildContext context) {
    return LinearProgressIndicator(
      value: value,
      valueColor: AlwaysStoppedAnimation(Colors.red),
      backgroundColor: Colors.grey,
    );
  }
}
